package com.zj.album.graphy.views;

import android.content.Context;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

import com.squareup.picasso.Picasso;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

/**
 * Created by zhaojie on 2018/2/7.
 */

public class RecyclerImageView extends android.support.v7.widget.AppCompatImageView {

    private SoftReference<RecyclerImageView> soft_Image;
    private String uri;
    private IHandler handler;
    private int w, h;

    public RecyclerImageView(Context context) {
        this(context, null, 0);
    }

    public RecyclerImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RecyclerImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        soft_Image = new SoftReference(this);
    }

    /**
     * set your Image bitmap;
     *
     * @param uri a local uri for image
     * @param w   your bitmap resize width
     * @param h   your bitmap resize height
     */
    public void setImageUri(String uri, int w, int h) {
        this.w = w;
        this.h = h;
        if (handler == null) handler = new IHandler(this);
        this.uri = uri;
        handler.sendEmptyMessageDelayed(200, 100);
    }

    private void setImg() {
        Picasso.with(soft_Image.get().getContext()).load(soft_Image.get().uri).centerCrop().resize(soft_Image.get().w, soft_Image.get().h).into(soft_Image.get());
    }

    private static class IHandler extends android.os.Handler {

        private WeakReference<RecyclerImageView> weak_ImageView;

        public IHandler(RecyclerImageView imageView) {
            this.weak_ImageView = new WeakReference<>(imageView);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 200:
                    if (weak_ImageView != null && weak_ImageView.get() != null) {
                        weak_ImageView.get().setImg();
                    }
                    break;
            }
        }
    }

    public void clear() {
        if (handler != null) handler.removeCallbacksAndMessages(null);
        removeCallbacks(null);
        clearAnimation();
        setImageBitmap(null);
        setBackground(null);
        handler = null;
        uri = null;
        soft_Image.clear();
        soft_Image = null;
    }
}
